#include <dblib.h>
#include <params.h>
#include <nysiis.h>
#include <stdafx.h>
#include <constants.h>
#include <stdexcept>

#ifdef __cplusplus
extern "C" {
#endif

RETCODE __declspec(dllexport) xp_phon_nysiis(SRV_PROC *srvproc);

#ifdef __cplusplus
}
#endif

RETCODE __declspec(dllexport) xp_phon_nysiis(SRV_PROC *srvproc)
{
	RETCODE rc = XP_NOERROR;
	params *p1 = new params();
	params *p2 = new params();
	BYTE *translated = NULL;
	ULONG len;
	int numparams = params::getparamcount(srvproc);
	try
	{
		if (numparams != 2) {
			Dblib::printerror(srvproc, USAGE_NYSIIS);
			rc = XP_ERROR;
		}
		if (rc == XP_NOERROR) {
			params::getparam(srvproc, 1, p1);
			params::getparam(srvproc, 2, p2);
			if (p1->isoutput || !p2->isoutput) {
				Dblib::printerror(srvproc, USAGE_NYSIIS);
				rc = XP_ERROR;
			}
		}
		if (rc == XP_NOERROR) {
			nysiis n;
			translated = new BYTE[p1->length + 12];
			srv_bzero(translated, p1->length + 12);
			if (p1->length > 0)
				len = n.Translate(p1->cdata, translated, p1->length);
			else
				len = 0;
			if (len > 8) len = 8;
		}
	} catch (std::exception ex) {
		Dblib::printerror(srvproc, ERR_NYSIIS_EXCEPTION);
		rc = XP_ERROR;
	}
	if (rc == XP_NOERROR)
		srv_paramsetoutput(srvproc, 2, translated, len, FALSE);
	else
		srv_paramsetoutput(srvproc, 2, (BYTE *)"", 0, TRUE);
  	// Now return the number of rows processed
	srv_senddone(srvproc, SRV_DONE_MORE, (DBUSMALLINT)0, (DBINT)0);
	if (p1 != NULL)
		delete p1;
	p1 = NULL;
	if (p2 != NULL)
		delete p2;
	p2 = NULL;
	if (translated != NULL)
		delete translated;
	translated = NULL;
	return rc;
}

